package com.lwm.tx.program.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * Spring 配置类 等同于bean.xml
 *
 * @author liweimin
 * @Configuration 指定当前类是一个配置类，配置类作为AnnotationConfigApplicationContext参数时，可以省略，多个配置时要写
 * @ComponentScan 指定Spring容器创建时要扫描的包
 * @Bean 把当前方法的返回值 存入Spring容器,bean-id默认值当前方法名称
 * @import 用于导入其他的配置类 使用Import注解的类 都是主配置类/父配置类 配置有参数 Spring回去容器中寻找 bean--->Autowired
 * @PropertySource： 配置源
 * @date 2021/6/10 11:50
 * @since
 */
@Configuration
@EnableTransactionManagement
@EnableAspectJAutoProxy
@ComponentScan(basePackages = {"com.lwm"})
@PropertySource("classpath:jdbc.properties")
public class SpringConfiguration {
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.name}")
    private String name;
    @Value("${jdbc.password}")
    private String password;


    @Bean(name = "dataSource")
    public DataSource getDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUsername(name);
        dataSource.setPassword(password);
        dataSource.setUrl(url);
        dataSource.setDriverClassName(driver);
        return dataSource;
    }

    @Bean(name = "jdbcTemplate")
    public JdbcTemplate getJdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean(name = "txManager")
    public TransactionManager getTxManager(DataSource dataSource) {
        TransactionManager  transactionManager = new DataSourceTransactionManager(dataSource);
        return transactionManager;
    }
}
